package com.cit.draw.redis;


import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class is for Json and Jackson object serialization;
 * 
 * @author Vincent Zou
 * 
 */
public class EntitySerializer {
	private ObjectMapper mapper = new ObjectMapper();

	private static final Logger log = LoggerFactory
			.getLogger(RedisCachingProvider.class);

	public EntitySerializer() {
		mapper.enableDefaultTyping();
	}

	public byte[] serialize(PersistedCacheObject o) {

		try {
			return mapper.writeValueAsBytes(o);
		} catch (JsonGenerationException e) {
			log.error(
					"Exception occurred when make {} serialization using Json",
					o.getClass(), e);
		} catch (JsonMappingException e) {
			log.error(
					"Exception occurred when make {} serialization using Json",
					o.getClass(), e);
		} catch (IOException e) {
			log.error(
					"Exception occurred when make {} serialization using Json",
					o.getClass(), e);
		}
		return null;

	}

	public PersistedCacheObject deserialize(byte[] bytes) {

		try {

			return mapper.readValue(bytes, PersistedCacheObject.class);

		} catch (JsonParseException e) {
			log.error(
					"Exception occurred when make deserialization using Json",
					e);
		} catch (JsonMappingException e) {
			log.error(
					"Exception occurred when make deserialization using Json",
					e);
		} catch (IOException e) {
			log.error(
					"Exception occurred when make deserialization using Json",
					e);
		}

		return null;
	}
}